package com.skydroid.fpvplayerdemo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.skydroid.fpvplayer.FPVWidget;
import com.skydroid.fpvplayer.LiveStreamHelper;
import com.skydroid.fpvplayer.LiveStreamListener;
import com.skydroid.fpvplayer.LiveStreamStatus;
import com.skydroid.fpvplayer.MyLogger;
import com.skydroid.fpvplayer.PlayerType;
import com.skydroid.fpvplayer.RtspTransport;
import com.skydroid.fpvplayer.VideoDecoderCallBack;

import java.nio.ByteBuffer;

/**
 * @author 咔一下
 * @date 2023/10/16 14:48
 * @email 1501020210@qq.com
 * @describe
 */
public class MainActivityForJava extends AppCompatActivity {

    FPVWidget fpvWidget = null;
    View mapWidget = null;
    FrameLayout switchVideoMapLayout = null;
    LiveStreamHelper liveStreamHelper = new LiveStreamHelper();

    LiveStreamListener liveStreamListener = new LiveStreamListener() {
        @Override
        public void onLiveStreamStatus(LiveStreamStatus status, long timestamp_us) {
            MyLogger.kLog().e("直播流状态:" + status + " " + timestamp_us);
        }
    };

    boolean isLiveStart = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Settings settings = new Settings(getApplicationContext());
        //去掉标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        fpvWidget = findViewById(R.id.fpvWidget);
        mapWidget = findViewById(R.id.map);
        switchVideoMapLayout = findViewById(R.id.switch_video_map);
        findViewById(R.id.btnUrl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String lastUrl = settings.getLastUrl();
                if (TextUtils.isEmpty(lastUrl)){
                    lastUrl = Settings.C10;
                }
                InputUrlDialogFragment.createDialog("确定", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {
                        if (TextUtils.isEmpty(s)){
                            return;
                        }
                        settings.setLastUrl(s);
                        fpvWidget.setUrl(s);
                        fpvWidget.stop();
                        fpvWidget.start();
                    }
                }, "取消", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {

                    }
                },lastUrl).show(getSupportFragmentManager(),"action_url");
            }
        });
        findViewById(R.id.btnPushVideo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String lastPushUrl = settings.getLastPushUrl();
                String pb;
                if (isLiveStart){
                    pb = "停止直播";
                }else{
                    pb = "开始直播";
                }
                InputUrlDialogFragment.createDialog(pb, new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {
                        if (TextUtils.isEmpty(s)){
                            return;
                        }
                        if (isLiveStart){
                            liveStreamHelper.stop();
                            isLiveStart = false;
                        }else{
                            settings.setLastPushUrl(s);
                            //内部有重连机制，开发者只需要关注相关状态
                            liveStreamHelper.start(s);
                            isLiveStart = true;
                        }
                    }
                }, "取消", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {

                    }
                },lastPushUrl).show(getSupportFragmentManager(),"action_url");
            }
        });
        String url = settings.getLastUrl();
        //使用硬解
        fpvWidget.setUsingMediaCodec(true);

        //使用软解
//        fpvWidget.setUsingMediaCodec(false);

        //设置播放地址
        fpvWidget.setUrl(TextUtils.isEmpty(url) ? Settings.C10 : url);

        //使用云卓播放器(如果是H16遥控器，建议使用IJKPlayer播放器)
        fpvWidget.setPlayerType(PlayerType.ONLY_SKY);

        //使用IJKPlayer播放器
//        fpvWidget.setPlayerType(PlayerType.ONLY_IJK);

        //RTSP流TCP/UDP连接
        fpvWidget.setRtspTranstype(RtspTransport.AUTO);

        //开始播放
        fpvWidget.start();

        mapWidget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFullVideo){
                    switchVideoMap();
                }
            }
        });

        fpvWidget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFullVideo){
                    switchVideoMap();
                }
            }
        });


        fpvWidget.setVideoDecoderCallBack(new VideoDecoderCallBack() {
            @Override
            public void onYUV(@NonNull ByteBuffer byteBuffer, int width, int height, int pixel_format) {
                liveStreamHelper.putYUV(byteBuffer, width, height, pixel_format);
            }
        });

        //设置直播流状态监听器
        liveStreamHelper.addListener(liveStreamListener);

        /**
         * 配置编码器相关属性
         */
        liveStreamHelper.setBitrate(1000000); //比特率
        liveStreamHelper.setFrameRate(15);//输出帧率
        liveStreamHelper.setVideoSize(640,360); //输出分辨率
        liveStreamHelper.setUseSoftEncoder(true); //true:软编码（X264），false:硬编码

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //停止播放
        fpvWidget.stop();
        liveStreamHelper.removeListener(liveStreamListener);
        if (isLiveStart){
            liveStreamHelper.stop();
            isLiveStart = false;
        }
    }

    private boolean isFullVideo = false;
    public void switchVideoMap() {
        if (isFullVideo){
            //设置交换图层后的宽高
            FrameLayout.LayoutParams fpvLayoutParams = (FrameLayout.LayoutParams)fpvWidget.getLayoutParams();
            fpvLayoutParams.width = PxUtils.dp2px(this,240);
            fpvLayoutParams.height = PxUtils.dp2px(this,135);
            fpvLayoutParams.gravity = Gravity.BOTTOM | Gravity.START;
            fpvWidget.setLayoutParams(fpvLayoutParams);
            FrameLayout.LayoutParams mapLayoutParams = (FrameLayout.LayoutParams)mapWidget.getLayoutParams();
            mapLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            mapLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            mapWidget.setLayoutParams(mapLayoutParams);
            //交换图层
            switchVideoMapLayout.removeView(fpvWidget);
            switchVideoMapLayout.addView(fpvWidget);
            isFullVideo = false;
        }else{
            //设置交换图层后的宽高
            FrameLayout.LayoutParams fpvLayoutParams = (FrameLayout.LayoutParams)fpvWidget.getLayoutParams();
            fpvLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            fpvLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            fpvWidget.setLayoutParams(fpvLayoutParams);
            FrameLayout.LayoutParams mapLayoutParams = (FrameLayout.LayoutParams)mapWidget.getLayoutParams();
            mapLayoutParams.width = PxUtils.dp2px(this,240);
            mapLayoutParams.height = PxUtils.dp2px(this,135);
            mapLayoutParams.gravity = Gravity.BOTTOM | Gravity.START;
            mapWidget.setLayoutParams(mapLayoutParams);
            //交换图层
            switchVideoMapLayout.removeView(mapWidget);
            switchVideoMapLayout.addView(mapWidget);
            isFullVideo = true;
        }
    }
}
